<script lang="ts" context="module">
  import type { Load } from "@sveltejs/kit/types/internal";

  export const load: Load = async({ fetch, params }) => {
    try {
      const res: {scope: Scope} = await fetch(`/api/scopes/${params.scope.split("-")[0]}`).then(r => r.json());

      return {
        props: {
          ...res,
        },
        stuff: {
          scope: res.scope,
          scopePath: params.scope,
        }
      };
    } catch(_) {}

		return {fallthrough: true} as any;
	}

  const STATUS_ORDER = [
    Status.Active,
    Status.Background,
    Status.Available,
    Status.Blocked,
    Status.Completed,
    Status.Failed,
    Status.Dropped,
  ]
</script>

<script lang="ts">
  import type Scope from "$lib/models/scope";
  import Header from "$lib/components/layout/Header.svelte";
  import Status from "$lib/models/status";
  import MenuCategory from "$lib/components/layout/MenuCategory.svelte";
  import type { ProjectEntry } from "$lib/models/project";
  import MenuItem from "$lib/components/layout/MenuItem.svelte";
  import {page} from "$app/stores";
import sluggify from "$lib/utils/slugify";

  export let scope: Scope;

  let projects = scope.projects;
  let projectsByStatus: Record<Status, ProjectEntry[]>;

  $: projectsByStatus = projects.reduce((p, c) => ({...p, [c.status]: [...p[c.status], c]}), {
    0: [], 1: [], 2: [], 3: [], 4: [], 5: [], 6: [],
  })
</script>

<div class="scope-layout">
  <div class="column main">
    <slot></slot>
  </div>
  <div class="column side">
    <Header subtitle={scope.name}>{scope.abbreviation}</Header>
    <MenuCategory title="Scope">
      <MenuItem href="/{$page.  stuff.scopePath}">Overview</MenuItem>
      <MenuItem href="/{$page.stuff.scopePath}/history">History</MenuItem>
    </MenuCategory>
    {#each STATUS_ORDER as status (status)}
      {#if projectsByStatus[status].length > 0}
        <MenuCategory status={status}>
          {#each projectsByStatus[status] as project (project.id)}
            <MenuItem href="/{$page.stuff.scopePath}/project/{project.id}-{sluggify(project.name)}" subtitle={
              project.name.includes(": ") ? project.name.split(": ")[0] + ": " : ""
            }>{
              project.name.includes(": ") ? project.name.split(": ").slice(1).join(": ") : project.name
            }</MenuItem>
          {/each}
        </MenuCategory>
      {/if}
    {/each}
  </div>
</div>

<style lang="scss">
  div.scope-layout {
    display: flex;
    flex-direction: row-reverse;
    flex-basis: 100%;
    flex: 1;

    width: 90ch;
    max-width: 95%;
    margin: auto;

    @media screen and (max-width: 600px) {
      width: 100%;
      flex-direction: column;
    }
  
    > div.column {
      display: flex;
      flex-direction: column;
      flex: 5;

      &.side {
        flex: 2;
  
        h2 {
          margin: 0;
          margin-top: 1em;
          font-size: 1em;
        }
      }
    }
  }
</style>